# 为组织架构提供数据转化
from django.core.cache import cache
from django.core.paginator import Paginator
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render

from apps.config.models import Dept_model
from apps.config.serializers import Dept_serializer, Menu_serializer


def Rec_Dept(datas):
    lists = []
    tree = {}
    parent_id = ''
    for i in datas:
        item = i
        tree[item['id']] = item
    root = None
    for i in datas:
        obj = i
        if not obj['tree_dept']:
            root = tree[obj['id']]
            lists.append(root)
        else:
            parent_id = obj['tree_dept']
            if 'children' not in tree[parent_id]:
                tree[parent_id]['children'] = []
            tree[parent_id]['children'].append(tree[obj['id']])
    return lists

# 获得depts页面
def depts_view(request):
    # 这里得获取其权限
    menu_list = cache.get('menu_list')
    menu_obj = Menu_serializer(menu_list, many=True)
    return render(request, 'depts/list.html', {'data':menu_obj.data})

# 获得其数据
def depts_list(request,id):
    if id==0:
        dept_list = Dept_model.objects.all()
        counts = Dept_model.objects.count()
    else:
        dept_list = Dept_model.objects.filter(tree_dept=id)
        counts = Dept_model.objects.filter(tree_dept=id).count()
    list=[]
    for i in dept_list:
        tree_dept = Dept_model.objects.filter(id=i.tree_dept_id).values_list('dept_name', flat=True)
        if len(tree_dept)==0:
            parent_dept=None
        else:
            parent_dept=tree_dept[0]
        dict = {}
        dict['id'] = i.id
        dict['dept_code'] = i.dept_code
        dict['dept_name'] = i.dept_name
        dict['tree_dept'] = i.tree_dept_id
        dict['dept_pname'] = parent_dept
        dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
        dict['now_status'] = i.now_status
        dict['remark_describe'] = i.remark_describe
        list.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    Result = {'code': 0, 'mes': '成功！', 'count': counts, 'data': res}
    return JsonResponse(Result)

# 下拉框选中相关
# 菜单权限下拉框视图
def depts_select(request):
    try:
        dept_list = Dept_model.objects.all()
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'dept下拉框出现问题！请联系管理员'})
    menu_obj = Dept_serializer(dept_list, many=True)
    return JsonResponse({'code': 0, 'data': menu_obj.data})



def depts_list1(request):
    try:
        dept_list = Dept_model.objects.filter()
    except Exception as e:
        return JsonResponse({'code':201,'msg':'Dept_model出现问题！'})
    ser_obj = Dept_serializer(dept_list, many=True)
    dept_lists = Rec_Dept(ser_obj.data)
    return JsonResponse({'code':0,'data':dept_lists})

# 组织机构添加视图
def depts_insert_view(request):
    return render(request, 'depts/insert.html')

# dept添加动作
@transaction.atomic
def depts_insert(request):
    # 判断是否具有权限
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '50500101' not in per_list:
        return JsonResponse({'code':201,'msg':'您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('dept_code')
    name = request.POST.get('dept_name')
    dept = request.POST.get('select')
    status = request.POST.get('now_status')
    remark = request.POST.get('remark_describe')
    try:
        Dept_model.objects.create(dept_code=code, dept_name=name, tree_dept_id=dept,
                                            now_status=status, remark_describe=remark,
                                  )
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        if e.args[0] == 1406:
            return JsonResponse({'code': 201, 'msg': '数据过长！'})
        if e.args[0] == 1062:
            return JsonResponse({'code': 202, 'msg': '唯一值出现重复！请检查部门代码。'})
        else:
            return JsonResponse({'code': 203, 'msg': '未知错误！'})
    return JsonResponse({'code': 0, 'msg': '添加成功！'})

# dept修改视图
def depts_edit_view(request):
    return render(request, 'depts/edit.html')

# dept修改动作
@transaction.atomic
def depts_edit(request,id):
    # 判断是否有权限id
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '50500102' not in per_list:
        return JsonResponse({'code':201,'msg':'您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('dept_code')
    name = request.POST.get('dept_name')
    dept = request.POST.get('select')
    status = request.POST.get('now_status')
    remark = request.POST.get('remark_describe')
    try:
        Dept_model.objects.filter(pk=id).update(dept_code=code,dept_name=name,tree_dept_id=dept,now_status=status,remark_describe=remark)
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        if e.args[0] == 1406:
            return JsonResponse({'code': 201, 'msg': '数据过长！'})
        if e.args[0] == 1062:
            return JsonResponse({'code': 202, 'msg': '唯一值出现重复！请检查部门代码。'})
        else:
            return JsonResponse({'code': 203, 'msg': '未知错误！'})
    return JsonResponse({'code': 0, 'msg': '修改成功！'})

# dept禁用动作
@transaction.atomic
def depts_del(request,id):
    m_list=cache.get('menu_list')
    per_list=[]
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '50500103' not in per_list:
        return JsonResponse({'code':201, 'msg':'您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    try:
        dept_obj = Dept_model.objects.get(pk=id)
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code': 202, 'msg': 'dept模块del动作出现问题！'})
    if dept_obj.now_status==0:
        dept_obj.now_status=1
        dept_obj.save()
        return JsonResponse({'code': 0, 'msg':'禁用成功！'})
    elif dept_obj.now_status==1:
        dept_obj.now_status = 0
        dept_obj.save()
        return JsonResponse({'code': 0, 'msg':'启用成功！'})

# 这里只查询机构名称，不包含部门名称
def depts_list2(request):
    try:
        dept_list = Dept_model.objects.filter(tree_dept=None)
    except Exception as e:
        return JsonResponse({'code':201,'msg':'Dept_model出现问题！'})
    ser_obj = Dept_serializer(dept_list, many=True)
    dept_lists = Rec_Dept(ser_obj.data)
    return JsonResponse({'code':0,'data':dept_lists})